package com.example.demo.config;

import com.example.demo.interceptor.SessionInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.ArrayList;
import java.util.List;

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    /**
     * 定义好的拦截器
     */
    @Autowired
    private SessionInterceptor sessionInterceptor;

    @Override
    public void addCorsMappings(CorsRegistry registry) {
//        方法一：明确指定允许的来源
//   .allowedOrigins("http://example.com", "http://anotherdomain.com") // 明确指定允许的来源
//        方法三：禁用allowCredentials(false)
        registry.addMapping("/**") // 对所有路径应用跨域配置
                .allowedOrigins("*") // 允许任何域进行跨域访问
//                .allowedOrigins("https://ninx.cafe", "http://localhost:5678")
//                .allowedOriginPatterns("https://ninx.cafe", "http://localhost:*") // 使用模式匹配
                .allowedMethods("GET", "POST", "PUT", "DELETE") // 允许的请求方法
                .allowedHeaders("*") // 允许的请求头
                .allowCredentials(false); // 是否允许发送凭据
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(sessionInterceptor)	// 配置定义好的拦截器
                .addPathPatterns("/**")	// 拦截所有请求
                .excludePathPatterns(getExcludePathPatterns());	// 忽略拦截的请求
    }

    // =================== private method ==================
    /**
     * <h5>功能:定义需要忽略拦截的请求</h5>
     *
     * @return
     */
    private List<String> getExcludePathPatterns(){
        List<String> excludePathPatternsList = new ArrayList<String>();
        excludePathPatternsList.add("/");
        excludePathPatternsList.add("/login");
        excludePathPatternsList.add("/download");
        excludePathPatternsList.add("/firmwareUpgrade/findByMap");
        excludePathPatternsList.add("/firmwareUpgrade/checkVersion");
        excludePathPatternsList.add("/firmwareUpgrade/usefulVersion");
        excludePathPatternsList.add("/css/**");
        excludePathPatternsList.add("/error/**");
        excludePathPatternsList.add("/img/**");
        excludePathPatternsList.add("/js/**");

        return excludePathPatternsList;
    }
}
